#! /usr/bin/python
# -*- coding: cp1250 -*-

import re, string, sys, glob, os, time, shutil
import pepe.p_utils.txt2pg as ppt
import pepe.p_sqlpg.pg as pg

def listTables():
    ''' '''
    res = []
    q = """select * from pg_tables where schemaname='public'"""
    for r in pg.Pg(q):
        res.append(r[1])
    return res

def dropTable(t):
    ''' '''
    #pg.Pg("""drop table %s""" % (t,))
    try:
        pg.Pg("drop table %s" % (t,))
        return 1
    except:
        return 0

def loadData(fMask='', cDelimiter=''):
    ''' '''
    files = glob.glob(fMask)
    for f in files:
        # table name
        t = f[:-4]
        # drop table if exists
        if t in listTables(): dropTable(t)

        p = ppt.TxtLoad()
        p.initFile(       inputFile=f
                        , colDelimiter=cDelimiter
                        , hasHeader=0
                        )
        p.dropTableBefore = 0
        #p.pgClientEncoding = 'UTF8'
        #p.pgClientEncoding = 'cp1250'
        p.createTable()
        p.loadData()

def cleanup_txt(txt):
    ''' cleanup of text rows before importing to pg db
    - replace all '\' with '_'
    -- '\' before column delimiters or '.' cause problems with COPY
    >>> cleanup_txt('Hello world\.|Hello world.')
    ('Hello world_.|Hello world.', 'Hello world\\\.|Hello world.')
    '''
    err = ''
    if re.search(r'\\', txt):
        err = txt
        txt = re.sub(r'\\', '_', txt)
    return (txt, err)

if __name__ == '__main__':
    ''' '''
    import doctest
    doctest.testmod()

    #print dropTable('AMOtb0409')
    #print dropTable('AMOtb0412')
    #print listTables()
    #print dropTable('aaa3')